const express = require('express');
const router = express.Router();
const productManagementService = require('../../services/productManagementService');
const adminAuth = require('../../middleware/adminAuth');
const { checkPermission } = require('../../middleware/permission');

/**
 * 获取商品列表
 */
router.get('/', adminAuth, checkPermission('product', 'read'), async (req, res) => {
  try {
    const {
      page = 1,
      limit = 20,
      search,
      category,
      type,
      status,
      isHot,
      isNew,
      isFeatured,
      isPointsProduct,
      stockStatus,
      sortBy = 'createdAt',
      sortOrder = 'DESC'
    } = req.query;

    const result = await productManagementService.getProductList({
      page: parseInt(page),
      limit: parseInt(limit),
      search,
      category,
      type,
      status: status !== undefined ? parseInt(status) : undefined,
      isHot,
      isNew,
      isFeatured,
      isPointsProduct,
      stockStatus,
      sortBy,
      sortOrder
    });

    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取商品列表失败',
      error: error.message
    });
  }
});

/**
 * 创建商品
 */
router.post('/', adminAuth, checkPermission('product', 'create'), async (req, res) => {
  try {
    const product = await productManagementService.createProduct(req.body, req.adminId);

    res.status(201).json({
      success: true,
      message: '商品创建成功',
      data: product
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 获取商品详情
 */
router.get('/:id', adminAuth, checkPermission('product', 'read'), async (req, res) => {
  try {
    const productId = parseInt(req.params.id);
    const result = await productManagementService.getProductById(productId);

    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(404).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 更新商品
 */
router.put('/:id', adminAuth, checkPermission('product', 'update'), async (req, res) => {
  try {
    const productId = parseInt(req.params.id);
    await productManagementService.updateProduct(productId, req.body, req.adminId);

    res.json({
      success: true,
      message: '商品更新成功'
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 删除商品
 */
router.delete('/:id', adminAuth, checkPermission('product', 'delete'), async (req, res) => {
  try {
    const productId = parseInt(req.params.id);
    await productManagementService.deleteProduct(productId, req.adminId);

    res.json({
      success: true,
      message: '商品删除成功'
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 调整商品库存
 */
router.post('/:id/stock', adminAuth, checkPermission('product', 'update'), async (req, res) => {
  try {
    const productId = parseInt(req.params.id);
    const { adjustment, reason } = req.body;

    if (adjustment === undefined || adjustment === 0) {
      return res.status(400).json({
        success: false,
        message: '库存调整数量不能为空或为0'
      });
    }

    const result = await productManagementService.adjustStock(
      productId, 
      parseInt(adjustment), 
      reason, 
      req.adminId
    );

    res.json({
      success: true,
      message: '库存调整成功',
      data: result
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 获取低库存商品
 */
router.get('/inventory/low-stock', adminAuth, checkPermission('product', 'read'), async (req, res) => {
  try {
    const { threshold = 10 } = req.query;
    const products = await productManagementService.getLowStockProducts(parseInt(threshold));

    res.json({
      success: true,
      data: products
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取低库存商品失败',
      error: error.message
    });
  }
});

/**
 * 获取商品概览统计
 */
router.get('/analytics/overview', adminAuth, checkPermission('product', 'read'), async (req, res) => {
  try {
    const overview = await productManagementService.getProductOverview();

    res.json({
      success: true,
      data: overview
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取商品概览失败',
      error: error.message
    });
  }
});

module.exports = router